package com.hzsparrow.business.base.config.shiro;

import com.hzsparrow.business.base.entity.HzsRole;
import com.hzsparrow.business.base.entity.HzsUser;
import com.hzsparrow.business.base.service.HzsRoleService;
import com.hzsparrow.business.base.service.HzsUserService;
import com.hzsparrow.business.base.vo.LoginVO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private HzsUserService hzsUserService;

    @Autowired
    private HzsRoleService hzsRoleService;

    /**
     * 身份验证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String account = token.getUsername();
        HzsUser user = hzsUserService.getByAccount(account).getData();
        if (user == null) {
            throw new UnknownAccountException("账号不存在！");
        }
        HzsRole role = hzsRoleService.getById(user.getHsrId()).getData();
        if (role == null) {
            throw new AccountException("角色信息错误！");
        }
        LoginVO loginEntity = new LoginVO();
        loginEntity.setUserId(user.getHsuId());
        loginEntity.setAccount(user.getHsuAccount());
        loginEntity.setUserName(user.getHsuName());
        loginEntity.setPowerGuid(user.getHsrId());
        loginEntity.setPowerName(role.getHsrName());
        loginEntity.setPowerType(role.getHsrType());
        loginEntity.setPhone(user.getMobile());
        loginEntity.setImgId(user.getImgId());
        return new SimpleAuthenticationInfo(loginEntity, user.getHsuPassword(), getName());
    }


    /**
     * 用户授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
